<template>
  <header-search placeholder="请输入数据集名称" :select-display="false" @on-search="onSearch">
    <template #button>
      <div class="flex justify-center">
        <a-button
          type="text"
          style="width: 36px; height: 36px"
          class="icon-only-btn"
          @click="fileTaskStore.changeTaskListOptions({ open: true })"
          ><i class="iconfont icon-tasklist-line"></i
        ></a-button>
      </div>
    </template>
  </header-search>
  <div class="card-wrap">
    <data-set-card
      v-for="(item, index) in dataList"
      :key="index"
      :data="item"
      @on-click="handleToDetail(item)"
      @on-download="handleDownLoad(item)"
      @okCancel="refreshDataList"
    />
  </div>
  <my-infinite-loading :empty="dataList.length === 0" img-margin-top="120px" :identifier="identifier" @infinite="loadData" />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { onUnmounted, ref } from 'vue'

  import DataSetCard, { DataSetCardData } from '@/components/DataSetCard/indx.vue'
  import { useFileTaskStore } from '@/components/FileTaskCard/upload-store'
  import HeaderSearch, { HeaderSearchEvents } from '@/components/HeaderSearch/index.vue'
  import manualMessage from '@/components/ManualMessage/index'
  import router from '@/router'
  import { collectionApi, customerPublicDataSetApi } from '@/services/api'

  export interface PageFormType {
    columns?: string
    limit: number
    objectName?: string
    offset: number
    order?: string
    favoriteType: number
  }

  const fileTaskStore = useFileTaskStore()

  const unsubscribe = fileTaskStore.pubSub.subscribe('changeTaskListOptions', () => {})

  const identifier = ref<number>(1)

  // 分页参数
  const pageForm = ref<PageFormType>({
    columns: 'createTime',
    limit: 20,
    objectName: '',
    offset: 1,
    order: 'desc',
    favoriteType: 3
  })

  const dataList = ref<DataSetCardData[]>([])
  // let page = 1
  export interface DataPublicRequest {
    columns?: string
    createTime?: string
    favoriteType?: number // 1:课程，2：项目案例，3：数据集，4：模型
    id: number
    limit?: number
    maxId?: number
    minId?: number
    objectId?: number // 收藏对象id
    objectName?: string
    offset?: number
    order?: string
    userId?: number
  }
  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = await collectionApi.bucketFavorite(pageForm.value)
      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }
      dataList.value.push(...records)
    } catch (error) {
      $state.error()
    }
  }

  // 刷新
  const refreshDataList = () => {
    pageForm.value.offset = 1
    dataList.value = []
    identifier.value = Date.now()
  }
  /*----------------------------------------- 筛选 --------------------------------*/
  const onSearch = (data: HeaderSearchEvents) => {
    pageForm.value.objectName = data.inputValue
    pageForm.value.offset = 1
    dataList.value = []
    identifier.value = Date.now()
  }

  /*----------------------------------------- 下载 --------------------------------*/
  const handleDownLoad = async (item: any) => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)
    try {
      // await dataManageApi.download({ id: data.id }, { isAddUid: true })
      const { data } = await customerPublicDataSetApi.download(
        { id: item.id },
        {
          isResponseAll: true,
          timeout: 300000 //设置超时时长5min
        }
      )
      if (data.code === 'SYSTEM-100000') {
        manualMessage.destroy()
        await message.success({ content: '成功添加至任务队列', icon: '', key: 'downloading', duration: 2 })
        fileTaskStore.changeTaskListOptions({
          open: true,
          key: '2',
          showDownFailed: false
        })
      } else {
        console.log('下载失败')
        manualMessage.destroy()
        message.error({ content: data.message, key: 'downloading', duration: 2 })
      }
    } catch (error) {
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }

  /*----------------------------------------- 详情 --------------------------------*/
  const handleToDetail = (item: any) => {
    router.push(`/data-set/public-data-detail/${item.id}?parent=/data-set/list/favorite&parentName=我的收藏`)
  }

  onUnmounted(() => {
    unsubscribe()
  })
</script>

<style lang="less" scoped>
  .card-wrap {
    display: grid;
    width: 100%;
    grid-template-columns: repeat(auto-fill, minmax(329px, 1fr));
    grid-gap: 24px 20px;
  }
</style>
